package com.atguigu.dga.dolphinscheduler.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.dga.dolphinscheduler.bean.TDsTaskDefinition;
import com.atguigu.dga.dolphinscheduler.mapper.TDsTaskDefinitionMapper;
import com.atguigu.dga.dolphinscheduler.service.TDsTaskDefinitionService;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tubage
 * @since 2024-03-19
 */
@Service
@DS("dolphinscheduler")
public class TDsTaskDefinitionServiceImpl extends ServiceImpl<TDsTaskDefinitionMapper, TDsTaskDefinition> implements TDsTaskDefinitionService {
    //
    @Value("${default.datawarehouse.database}")
    private String defalutDwDatabse;

    // TODO 1 获取DS工作定义 同时处理好提取sql，补充mainAssess中

    @Override
    public List<TDsTaskDefinition> getTDsTaskDefinitionList() {
        List<TDsTaskDefinition> tDsTaskDefinitions = list(
                new QueryWrapper<TDsTaskDefinition>()
                        .eq("task_type", "SHELL")
                        //.like("name", defalutDwDatabase + ".%")
        );

        // TODO 2 提取sql 处理一下 封装方法extractSqlFromTDsTaskDefinition
        for (TDsTaskDefinition tDsTaskDefinition : tDsTaskDefinitions) {
            extractSqlFromTDsTaskDefinition(tDsTaskDefinition);
        }
        return tDsTaskDefinitions;
    }

    // TODO 3 sql提取方法
    private void extractSqlFromTDsTaskDefinition(TDsTaskDefinition tDsTaskDefinition ) {
        // 获取rawScript
        String taskParamsJsonStr = tDsTaskDefinition.getTaskParams();
        JSONObject taskParamJsonObj = JSON.parseObject(taskParamsJsonStr);
        String rawScript = taskParamJsonObj.getString("rawScript");

        if(rawScript == null) {
            return;
        }

        // sql开始位置 通过with 或者insert判定
        int startIndex = -1;
        int withIndex = rawScript.indexOf("with");
        if (withIndex == -1) {
            startIndex = rawScript.indexOf("insert");
        } else {
            startIndex = withIndex;
        }
        if(startIndex == -1) {
            return;
        }

        // sql结束位置 通过" 或者;判定
        int endIndex = -1;
        int semiIndex = rawScript.indexOf(";", startIndex);
        if(semiIndex == -1) {
            endIndex = rawScript.indexOf("\"", startIndex);
        }else {
            endIndex = semiIndex;
        }

        String taskSql = rawScript.substring(startIndex, endIndex);
        tDsTaskDefinition.setTaskSQl(taskSql);


    }
}
